/**
 * FormData 辅助工具
 */

/**
 * 创建文件上传的 FormData
 * @param content 文件内容
 * @param filename 文件名
 * @param contentType 内容类型
 * @returns FormData
 */
export function createFileFormData(
  content: string | Blob,
  filename: string,
  contentType: string = 'text/plain',
): FormData {
  const formData = new FormData();

  let blob: Blob;
  if (content instanceof Blob) {
    blob = content;
  }
  else {
    blob = new Blob([content], { type: contentType });
  }

  formData.append('file', blob, filename);
  return formData;
}

/**
 * 调试 FormData 内容
 * @param formData FormData 对象
 */
export function debugFormData(formData: FormData): void {
  console.log('FormData entries:');
  for (const [key, value] of formData.entries()) {
    if (value instanceof File) {
      console.log(`${key}:`, {
        name: value.name,
        size: value.size,
        type: value.type,
        lastModified: value.lastModified,
      });
    }
    else {
      console.log(`${key}:`, value);
    }
  }
}

/**
 * 检查请求头是否适合 FormData
 * @param headers 请求头
 * @returns boolean
 */
export function isFormDataCompatible(headers: Headers | Record<string, string>): boolean {
  const contentType = headers instanceof Headers
    ? headers.get('content-type')
    : headers['content-type'] || headers['Content-Type'];

  // FormData 应该没有设置 Content-Type 或者是 multipart/form-data
  return !contentType || contentType.startsWith('multipart/form-data');
}
